print(0)
import pyautogui
import pyautogui as g
from datetime import datetime
import io
from cnocr import CnOcr
import time
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import cv2
import uuid
import pyperclip
print(0.1)

def mouse_shake(distance=100, duration=0.2, times=1):
    """
    让鼠标在当前位置左右晃动。

    参数：
    distance (int): 晃动的水平距离，默认为50像素。
    duration (float): 每次移动的持续时间（秒），默认为0.2秒。
    times (int): 晃动的次数，默认为5次。
    """
    # 获取鼠标当前位置
    start_x, start_y = pyautogui.position()

    # 鼠标左右晃动
    for i in range(times):
        # 向右移动
        pyautogui.moveTo(start_x + distance, start_y, duration=duration)
        # 向左移动
        pyautogui.moveTo(start_x - distance, start_y, duration=duration)

    # 返回到初始位置
    pyautogui.moveTo(start_x, start_y, duration=0.5)

def screenshot_full_screen():
    """
    截取全屏并返回图像对象。

    返回:
        PIL.Image: 全屏截图的图像对象。
    """
    screenshot = pyautogui.screenshot()
    return screenshot

def write_image_to_memory(image):
    """
    将图像对象写入内存。

    参数:
        image (PIL.Image): 要写入内存的图像对象。

    返回:
        io.BytesIO: 包含图像数据的内存文件对象。
    """
    memory_file = io.BytesIO()
    image.save(memory_file, format='PNG')
    memory_file.seek(0)
    return memory_file

def ocr_from_memory(memory_file):
    """
    从内存中的图像数据进行文字识别。

    参数:
        memory_file (io.BytesIO): 包含图像数据的内存文件对象。

    返回:
        list: 识别出的文字信息，包含文字内容和坐标中间值。
    """
    # 将内存文件转换为 PIL 图像对象
    image = Image.open(memory_file)
    print(0.31)
    #image.show()
    #ocr = CnOcr()
    print(0.32)
    # 进行 OCR 识别
    result = ocr.ocr(image)
    print(0.33)
    

    
    return result
def search(str1):
    screenshot = screenshot_full_screen()
    print(0.2)
    memory_file = write_image_to_memory(screenshot)
    print(0.3)
    ocr_result = ocr_from_memory(memory_file)
    print(0.4)
    image = Image.open(memory_file)
    print(0.5)
    draw = ImageDraw.Draw(image)
    font_path = "simhei.ttf"  # 黑体字体文件路径
    font_size = 16  # 字体大小
    font = ImageFont.truetype(font_path, font_size)
    font1 = ImageFont.truetype(font_path, 50)
    #print('xxxx****')
    text_color = (0, 255, 0)
    text_color1 = (255, 0, 0) 
    for item  in ocr_result:
        #print(item['text'])
        #pyautogui.moveTo(item['position'])
        box = item['position']
        box1=(box[0][0],box[0][1],box[2][0],box[2][1])
        # 计算中间值
        x_center = int((box[0][0] + box[1][0] + box[2][0] + box[3][0])/4)      
        y_center = int((box[0][1] + box[1][1] + box[2][1] + box[3][1])/4)
        try:
            draw.rectangle(box1, outline="blue",fill="white", width=3)
        except:
            print(box,box1)
        text=item['text']
        text_position = (box[0][0], box[0][1])  # 文字位置
         # 文字颜色（红色）
        # 替换 box 为 position，并存储中间值
        item['position'] = (x_center, y_center)
        try:
            draw.text(text_position, text,font=font, fill=text_color)
        except:
            print(box,box1)
        draw.text((100,100), str1,font=font1, fill=text_color1)

        if str1 in item['text']:
            draw.rectangle(box1, outline="red",fill="white", width=3)
            draw.text(text_position, text,font=font, fill=text_color1)
            #print('************')
            #pyautogui.moveTo(item['position'])
            #time.sleep(0.3)
            #g.click()
            #time.sleep(3)
            
    #image.show()
    image_cv = np.array(image)
    image_cv = cv2.cvtColor(image_cv, cv2.COLOR_RGB2BGR)
    random_name = str(uuid.uuid4())
    #print('random_name',random_name)

    # 创建一个全屏窗口
    cv2.namedWindow(random_name,cv2.WINDOW_NORMAL)
    #cv2.setWindowProperty(random_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN,cv2.WND_PROP_TOPMOST, 1)
    cv2.setWindowProperty(random_name,cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
    cv2.setWindowProperty(random_name,cv2.WND_PROP_TOPMOST,1)

    

    # 显示图像
    cv2.imshow(random_name, image_cv)
    #print('show pic')
    cv2.waitKey(3000)
    #cv2.destroyAllWindows()
    cv2.destroyWindow(random_name)
    for item  in ocr_result:
        if str1 in item['text']:
            #draw.rectangle(box1, outline="red",fill="white", width=3)
            #draw.text(text_position, text,font=font, fill=text_color)
            #print('here,#########')
            pyautogui.moveTo(item['position'][0],item['position'][1],1)
            #mouse_shake()
            pyautogui.mouseDown();
            time.sleep(0.5)
            pyautogui.mouseUp()
            
            g.click()
            time.sleep(1)
    return item['position']
       
def action(*arg):
    global ocr
    ocr = CnOcr()

    for item in arg:
        if 'text' in item.keys():
            search(item['text'])
            if 'time' in item.keys():
                time.sleep(item['time'])
        elif 'write' in item.keys():
            pyperclip.copy(item['write'])  # 将中文文本复制到剪贴板
            pyautogui.hotkey("ctrl", "v")
        elif 'hotkey' in item.keys():
            pyautogui.hotkey(item['hotkey'])
            time.sleep(1)
            
#口
#X

#action({'hotkey':('win', 'r')},{'write':'msedge'},{'hotkey':('enter')},{'hotkey':('F11')},{'text':'京东','time':3},{'text':'家用电器','time':3},{'text':'平板电视','time':3},{'hotkey':('alt','F4')})

action(
    {'hotkey':('win', 'r')},
    {'write':'notepad'},
    {'hotkey':('enter')},
    {'write':'现在开始演示'},
    {'hotkey':('enter')},
    {'hotkey':('alt','F4')},
    {'text':'不保存'},
    {'hotkey':('win', 'r')},
    {'write':'msedge'},
    {'hotkey':('enter')},
    {'hotkey':('F11')},
    {'text':'京东','time':3},
    {'text':'家用电器','time':3},
    {'text':'平板电视','time':3},
    {'hotkey':('alt','F4')},
    {'hotkey':('win', 'r')},
    {'write':'notepad'},
    {'hotkey':('enter')},
    {'write':'演示结束'},
    {'hotkey':('enter')},
    {'write':'谢谢观看'},
    {'hotkey':('alt','F4')},
    )